#pragma once
#include <iostream>
#include "Task.hpp"
#include <queue>
#include "pthread.h"
#include "Log.hpp"

#define NUM 5

class ThreadPool
{
private:
    int _num;
    std::queue<Task> _task_queue;
    pthread_mutex_t _lock;
    pthread_cond_t _cond;
    bool _stop;

    ThreadPool(int num = NUM) : _num(num), _stop(false)
    {
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ThreadPool(const ThreadPool &x) {}
    static ThreadPool *single_instatic;

public:
    static ThreadPool *GetInstance()
    {
        static pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER;
        if (single_instatic == nullptr)
        {
            pthread_mutex_lock(&Mutex);
            if (single_instatic == nullptr)
            {
                single_instatic = new ThreadPool();
                single_instatic->InitThreadPool();
            }
            pthread_mutex_destroy(&Mutex);
        }
        return single_instatic;
    }
    bool IsStop()
    {
        return _stop;
    }
    bool TaskQueueIsEmpty()
    {
        return _task_queue.empty();
    }
    void ThreadWait()
    {
        pthread_cond_wait(&_cond, &_lock);
    }
    void ThreadWakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void Lock()
    {
        pthread_mutex_lock(&_lock);
    }
    void UnLock()
    {
        pthread_mutex_unlock(&_lock);
    }
    bool InitThreadPool()
    {
        for (int i = 0; i < _num; i++)
        {
            pthread_t tid;
            if (0 != pthread_create(&tid, nullptr, ThreadRoutine, this))
            {
                LOG(FATAL, "create thread pool error");
                return false;
            }
        }
        LOG(INFO, "create thread pool success");
        return true;
    }

    static void *ThreadRoutine(void *args)
    {
        ThreadPool *tp = (ThreadPool *)args;

        while (true)
        {
            Task task;
            tp->Lock();
            while (tp->TaskQueueIsEmpty())
            {
                tp->ThreadWait();
            }
            tp->PopTask(task);
            tp->UnLock();
            task.ProcessOn();
        }
    }
    void PushTask(const Task &task)
    {
        Lock();
        _task_queue.push(task);
        UnLock();
        ThreadWakeup();
    }
    void PopTask(Task &task)
    {
        task = _task_queue.front();
        _task_queue.pop();
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }
};

ThreadPool *ThreadPool::single_instatic = nullptr;
